03. The `this` Keyword
OOJS L3 27 - This Keyword Intro V2
this in Constructor Functions
In the previous section, we saw this right inside a constructor function. Here's another example:
function Cat(name) {
this.name = name;
this.sayName = function () {
console.log(`Meow! My name is ${this.name}`);
};
}
const bailey = new Cat('Bailey');
In the above Cat() constructor, the function that sayName references this.name. Back in Lesson 1, we saw this used in methods. But in Cat()'s case, what exactly does this refer to?
As it turns out, when invoking a constructor function with the new operator, this gets set to the newly-created object! Let's check out what the new bailey object looks like:
{
name: 'Bailey',
sayName: function () {
console.log(`Meow! My name is ${this.name}`);
}
}
In the snippet above, notice that this is outside a constructor function (i.e., in a method). As we saw in Lesson 1, when you say this in a method, what you're really saying is "this object" or "the object at hand." As a result, the sayName() method can use this to access the name property of that object! This makes the following method call possible:
bailey.sayName();
// 'Meow! My name is Bailey'
Note: For a refresher on how a method uses this to access an object on which it was called, feel free to review Invoking Object Methods in Lesson 1.
When is this Assigned?
A common misconception is that this refers to the object where it is defined. This is not the case!
The value of this is actually not assigned to anything until an object calls the method where this is used. In other words, the value assigned to this is based on the object that invokes the method where this is defined. Let's look at an example:
const dog = {
bark: function () {
console.log('Woof!');
},
barkTwice: function () {
this.bark();
this.bark();
}
};
Let's go ahead and invoke both of dog's methods:
dog.bark();
// Woof!
dog.barkTwice();
// Woof!
// Woof!
We know that when we call dog.bark(); (or dog.barkTwice();) a variable this gets set. Since this can access the object it was called on, barkTwice can use this to access the dog object, which contains the bark method.
But what if we just wrote bark(); instead of this.bark(); in barkTwice? The function would have first looked for a local variable named bark in the scope of barkTwice. If bark isn't found, it would have looked further up the scope chain.
To tie things all together: this.bark(); tells barkTwice to look at dog -- the object that the method was called on -- to find bark.
SOLUTION:
- Using `this`, methods can access and manipulate an object's properties
- `this` is a reserved word in JavaScript
SOLUTION:
The newly-created object, referenced by `sanFrancisco`What Does this Get Set To?
At this point, we've seen this in many different contexts, such as within a method, or referenced by a constructor function. Let's now organize our thoughts and bring it all together!
There are four ways to call functions, and each way sets this differently.
First, calling a constructor function with the new keyword sets this to a newly-created object. Recall that creating an instance of Cat earlier had set this to the new bailey object.
On the other hand, calling a function that belongs to an object (i.e., a method) sets this to the object itself. Recall that earlier, the dog object's barkTwice() method was able to access properties of dog itself.
Third, calling a function on its own (i.e., simply invoking a regular function) will set this to window, which is the global object if the host environment is the browser.
function funFunction() {
return this;
}
funFunction();
// (returns the global object, `window`)
The fourth way to call functions allows us to set this ourselves! Don't worry about this approach for now; we'll take a deep dive in the very next section.
Whew -- that was a lot of this! Let's compartmentalize these findings in the video below:
OOJS L3 33 - 'This' Grid V1
If a constructor function is called with the new operator, the value of this is set to the newly-created object. If a method is invoked on an object, this is set to that object itself. And if a function is simply invoked, this is set to the global object: window.
SOLUTION:
`building`SOLUTION:
`window`Summary
Functions, objects, and this are all interconnected. When invoking constructor functions with the new operator, a this variable is set to the newly-created object. When invoking a method on an object, this is set to that object itself. And when invoking a function in a browser environment, this is set to window, otherwise known as the global object.
Along with all this, there is yet one more set of ways to invoke functions: with apply(), and with call(). Both methods share quite a few similarities, and they each allow us to specify how we want to set this. We'll take a look at each of them in detail next!
Further Research
- The this operator on MDN